import { ref, onUnmounted, reactive } from "vue";
import { ElMessage } from 'element-plus'

export const useWebSocket = (url) => {
    const ws = ref();
    const isConnected = ref(false);
    const messages = reactive([]);
    const error = ref(null);
    const heartConnected = ref(false)
    // 开启连接
    function connect() {
        ws.value = new WebSocket(url)
        // 连接开启
        ws.value.onopen = () => {
            isConnected.value = true;
            heartConnected.value = true
            ElMessage({
                message: '连接成功',
                type: 'success',
            })
            console.log('连接打开');
        };
        // 处理接收到的消息
        ws.value.onmessage = (event) => {
            if (JSON.parse(event.data).type) {
                console.log('连接正常')
                isConnected.value = true;
                heartConnected.value = true
            } else {
                messages.unshift(JSON.parse(event.data));
                console.log(`收到的消息: ${event.data}`);
            }
        };
        // 处理连接关闭事件
        ws.value.onclose = (event) => {
            isConnected.value = false;
            heartConnected.value = false
            if (event.code == 1006) {
                console.log('服务端错误')
                ElMessage({
                    message: `服务端错误`,
                    type: 'warning',
                    grouping: true,
                    repeatNum:1
                })
                connect()
            } else if (event.code == 1005) {
                console.log('客户端关闭连接')
                ElMessage({
                    message: `客户端关闭连接`,
                    type: 'warning',
                })
            }
 
        };
        // 处理错误事件
        ws.value.onerror = (err) => {
            error.value = err;
            isConnected.value = true;
            heartConnected.value = true;
            // ElMessage({
            //     message: `错误信息:${err}`,
            //     type: 'error',
            // })
        };
    }
    // 心跳检测
    setInterval(() => {
        if (ws.value && ws.value.readyState === WebSocket.OPEN) {
            ws.value.send(JSON.stringify({ type: 'ping' }));
        }
    }, 1000);
    // 发送消息
    function sendMessage(message) {
        if (ws.value && ws.value.readyState === WebSocket.OPEN) {
            ws.value.send(message);
        } else {
            isConnected.value = true;
            heartConnected.value = true
        }
    }

    // 断开 WebSocket 连接
    function disconnect() {
        if (ws.value) {
            ws.value.close();
        }
    }

    // 组件卸载时清理 WebSocket 连接
    onUnmounted(() => {
        disconnect();
    });
    return {
        ws,
        isConnected,
        heartConnected,
        messages,
        error,
        connect,
        sendMessage,
        disconnect
    };
}

